package com.cpic.nonauto.bloomfilter.lock;

import org.springframework.context.expression.MapAccessor;
import org.springframework.context.expression.MethodBasedEvaluationContext;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;

import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Map;

/**
 * @program: bloom-filter
 * @description: SpelExecutor
 * @packagename: com.cpic.nonauto.bloomfilter.lock
 * @author: admin
 * @date: 2020-07-31 16:30
 */
public class SpelExecutor {

    private final static SpelExecutor SPEL_EXECUTOR = new SpelExecutor();
    private final static SpelExpressionParser PARSER = new SpelExpressionParser();

    private SpelExecutor() {
    }

    public static SpelExecutor getInstance() {
        return SPEL_EXECUTOR;
    }

    public Expression getExpression(String script) {
        return PARSER.parseExpression(script);
    }

    public Object execute(String script, Method method, Object[] args) {

        Expression expression = getExpression(script);
        Map<String, Object> map = Collections.singletonMap("args", args);
        MethodBasedEvaluationContext methodBasedEvaluationContext = new MethodBasedEvaluationContext(map, method, args, new DefaultParameterNameDiscoverer());
        methodBasedEvaluationContext.getPropertyAccessors().add(new MapAccessor());
        /*#param0表示第一个参数、#param1表示第二个参数*/
        if (null != args) {
            for (int i = 0; i < args.length; i++) {
                methodBasedEvaluationContext.setVariable("param" + i, args[i]);
            }
        }
        return expression.getValue(methodBasedEvaluationContext);
    }

}
